package com.songshu.e.dubbo.api.service;

import com.aliyun.oss.OSSClient;
import com.songshu.e.dubbo.api.config.AliyunConfig;
import com.songshu.e.dubbo.api.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class PicUploadService {

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};

    //注入阿里云OSS服务对象
    @Autowired
    private OSSClient ossClient;

    //注入阿里云配置对象
    @Autowired
    private AliyunConfig aliyunConfig;

    public PicUploadResult upload(MultipartFile multipartFile) {
        //图片后缀名校验
        boolean isLegal = false;
        for (String type : IMAGE_TYPE){
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        //封装PicUploadResult对象,将文件的byte数组放到Result对象中
        PicUploadResult picUploadResult = new PicUploadResult();
        //如果图片后缀名不合法
        if (!isLegal){
            picUploadResult.setStatus("error");
            return picUploadResult;
        }

        //图片后缀名合法
        //创建文件新路径
        String filename = multipartFile.getOriginalFilename();
        String filepath = getFilePath(filename);

        //上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filepath,
                    new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            picUploadResult.setStatus("error");
            return picUploadResult;
        }

        //上传成功
        picUploadResult.setStatus("done");
        picUploadResult.setName(aliyunConfig.getUrlPrefix() + filepath);
        picUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return picUploadResult;
    }

    //创建文件目录
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
